package com.zy.experience_system.service.impl;

import com.zy.experience_system.dto.StuHomeworkDTO;
import com.zy.experience_system.dto.TestInformationDTO;
import com.zy.experience_system.entity.StuHomework;
import com.zy.experience_system.entity.TestInformation;
import com.zy.experience_system.form.FileForm;
import com.zy.experience_system.repository.StuHomeworkRepository;
import com.zy.experience_system.repository.TestInformationRepository;
import com.zy.experience_system.service.FileService;
import com.zy.experience_system.service.StuHomeworkService;
import com.zy.experience_system.service.TestService;
import com.zy.experience_system.util.FileUtil;
import com.zy.experience_system.vo.ImageVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private TestService testInformationService;
    @Autowired
    private TestInformationRepository testInformationRepository;
    @Autowired
    private StuHomeworkRepository stuHomeworkRepository;
    @Autowired
    private StuHomeworkService stuHomeworkService;

    private Logger log = LoggerFactory.getLogger("FileController");

    @Value("${file.upload.root.abpath}")
    private String filePath;

    @Value("${file.upload.root.repath}")
    private String repath;

    //端口号
    @Value("${server.port}")
    private String port;

    @Value("${file.upload.root.mdImageDir}")
    private String mdImageDir;

    @Override
    public void save(FileForm fileForm,HttpServletRequest request) throws Exception{
        String content = fileForm.getContent();
        String name = fileForm.getName();
        String typeId = fileForm.getTypeId();
        Integer testId = fileForm.getTestId();
        Integer homeworkId = fileForm.getHomeworkId();
        MultipartFile file = fileForm.getFile();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssS");
        // 得到格式化后的日期
        String format = sdf.format(new Date());
//        保存文件类型
        if (!typeId.equals("md")){
            // 获取上传的文件名称
            String fileName = file.getOriginalFilename();
            // 时间 和 日期拼接
            String newFileName = format + "_" + name + "_" +fileName;
            // 得到文件保存的位置以及新文件名
            String myFilePath = filePath + typeId +"/" ;
            String myRepath = repath + typeId + "/";
            File dest = new File(myFilePath + newFileName);
            try {
                // 上传的文件被保存了
                file.transferTo(dest);
                // 打印日志
                log.info("上传成功，当前上传的文件保存在 {}",myFilePath + newFileName);
                String urlDir="http:"+request.getHeader("Origin1").split(":")[1]+":"+port+myRepath + newFileName;
                log.info(urlDir);
                if (typeId.equals("doc")){
                    saveDoc(testId,urlDir);
                } else if (typeId.equals("mp4")){
                    saveMP4(testId,urlDir);
                } else {
                    saveHomeworkFile(homeworkId,urlDir);
                }
            } catch (IOException e) {
                log.error(e.toString());
            }
        } // 保存md类型
        else {
            try {
                String newFileName;
                if (name.equals("content")){
                    newFileName = format + "_" + name + "_" + testId;
                }
                else {
                    newFileName = format + "_" + name + "_" + homeworkId;
                }
                String myFilePath = filePath + typeId + "/"+ name +"/" + newFileName + ".md";
                String myRepath = repath + typeId + "/";
                FileUtil.string2File(content, myFilePath);
                log.info("上传成功，当前上传的文件保存在 {}",myFilePath + newFileName);
                String urlDir="http:"+request.getHeader("Origin1").split(":")[1]+":"+port+myRepath + newFileName + ".md";
                if (name.equals("comment")){
                    saveComment(homeworkId,urlDir);
                } else if (name.equals("answer")){
                    saveEssayAnswer(homeworkId,urlDir);
                } else if (name.equals("content")){
                    saveTestContent(testId,urlDir);
                }
            }catch (Exception e) {
                log.error(e.toString());
            }
        }
    }




    @Override
    public ImageVO saveImage(FileForm fileForm, HttpServletRequest request) {
        String content = fileForm.getContent();
        String name = fileForm.getName();
        String typeId = fileForm.getTypeId();
        if (!typeId.equals("image")){
            log.error("文件类型错误");
            return null;
        }
        MultipartFile file = fileForm.getFile();
        //上传的相对路径  /file/md/image/
        String imgAbPath=filePath+"md/"+"image/";
        //绝对路径对应urlpath   http://localhost:4000/file/homework/image/
        String imgUrlDir="http:"+request.getHeader("Origin1").split(":")[1]+":"+port+ mdImageDir;
        //返回对应的File类型f
        File f = FileUtil.upload(file, imgAbPath, name);
        ImageVO imageVO = new ImageVO();
        imageVO.setImage(imgUrlDir+f.getName());
        return imageVO;
    }


    @Override
    public void saveDoc(Integer testId,String doc){
        TestInformation testInformation = testInformationRepository.findById(testId).get();
        testInformation.setTestDoc(doc);
        TestInformationDTO testInformationDTO = new TestInformationDTO();
        BeanUtils.copyProperties(testInformation,testInformationDTO);
        testInformationService.save(testInformationDTO);
    }
    @Override
    public void saveMP4(Integer testId,String mp4){
        TestInformation testInformation = testInformationRepository.findById(testId).get();
        testInformation.setTestMp4(mp4);
        TestInformationDTO testInformationDTO = new TestInformationDTO();
        BeanUtils.copyProperties(testInformation,testInformationDTO);
        testInformationService.save(testInformationDTO);
    }
    @Override
    public void saveHomeworkFile(Integer homeworkId,String homeworkFile){
        StuHomework stuHomework = stuHomeworkRepository.findById(homeworkId).get();
        stuHomework.setHomeworkFile(homeworkFile);
        StuHomeworkDTO stuHomeworkDTO = new StuHomeworkDTO();
        BeanUtils.copyProperties(stuHomework,stuHomeworkDTO);
        stuHomeworkService.save(stuHomeworkDTO);
    }
    @Override
    public void saveComment(Integer homeworkId,String comment){
        StuHomework stuHomework = stuHomeworkRepository.findById(homeworkId).get();
        stuHomework.setComment(comment);
        StuHomeworkDTO stuHomeworkDTO = new StuHomeworkDTO();
        BeanUtils.copyProperties(stuHomework,stuHomeworkDTO);
        stuHomeworkService.save(stuHomeworkDTO);
    }
    @Override
    public void saveEssayAnswer(Integer homeworkId,String essayAnswer){
        StuHomework stuHomework = stuHomeworkRepository.findById(homeworkId).get();
        stuHomework.setEssayAnswer(essayAnswer);
        StuHomeworkDTO stuHomeworkDTO = new StuHomeworkDTO();
        BeanUtils.copyProperties(stuHomework,stuHomeworkDTO);
        stuHomeworkService.save(stuHomeworkDTO);
    }
    @Override
    public void saveTestContent(Integer testId,String testContent){
        TestInformation testInformation = testInformationRepository.findById(testId).get();
        testInformation.setTestContent(testContent);
        TestInformationDTO testInformationDTO = new TestInformationDTO();
        BeanUtils.copyProperties(testInformation,testInformationDTO);
        testInformationService.save(testInformationDTO);
    }
}
